<template>
  <div>
    <!-- 作业信息 -->
    <div class="course-info">
      <h2>作业详情 - {{ homework.name }}</h2>
      <el-card header="作业信息">
        <div>
          <el-row>
            <el-col :span="6" v-if="!editing">课程序号: {{ homework.courseId }}</el-col>
            <el-col v-else>
            <el-input v-model="homework.courseId"></el-input>
            </el-col>
            <el-col :span="6" v-if="!editing">授课教师: {{ homework.teacherId }}</el-col>
            <el-col v-else>
            <el-input v-model="homework.teacherId"></el-input>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-row>
            <el-col :span="6" v-if="!editing">发布日期: {{ homework.startTime }}</el-col>
            <el-col v-else>
              <el-date-picker
                    v-model="homework.startTime"
                    type="datetime"
                    placeholder="开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    date-format="MMM DD, YYYY"
                    time-format="HH:mm"
                  />
            </el-col>
            <el-col :span="6" v-if="!editing">截止日期: {{ homework.endTime }}</el-col>
            <el-col v-else>
            <el-date-picker
                    v-model="homework.endTime"
                    type="datetime"
                    placeholder="开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    date-format="MMM DD, YYYY"
                    time-format="HH:mm"
                  />
            </el-col>
          </el-row>
        </div>
        <div>
          <el-row>
            <el-col :span="6" v-if="!editing">
                算法设置:
              <span v-if="homework.method === '1'">按照教师评分等级分配</span>
              <span v-else>按照评阅次数分配</span>
              </el-col>
              <el-col :span="6" v-if="!editing">
                是否匿名:
              <span v-if="homework.anonymous === '1'">是</span>
              <span v-else>否</span>
            </el-col>
            <el-col v-else>
              <el-col>算法设置:
                <span><select v-model="homework.method">
                  <option value="1">按照教师评分等级分配</option>
                  <option value="0">按照评阅次数分配</option>
                </select></span>
              </el-col>
              <el-col>是否匿名:
                  <span><select v-model="homework.anonymous">
                    <option value="1">是</option>
                    <option value="0">否</option>
                  </select></span>
              </el-col>
            </el-col>
            <el-col>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-row>
        <el-col :span="6">
         <el-button @click="toggleEditing">{{ editing ? '取消' : '编辑' }}</el-button>
         <el-button @click="saveAnswer" :disabled="!editing">保存</el-button>
        </el-col>
      </el-row>
      </div>
        <div class="course-profile">
          <el-divider></el-divider>
          <h3>作业内容</h3>
          <p>{{ homework.profile }}</p>
        </div>
        <div class="course-profile">
          <el-upload
          class="upload-demo"
          ref="upload"
          action="http://123.57.192.191/api/homework/teacher-annex"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          :auto-upload="false"
          name="files"
          :data="{ homeworkId: $route.params.homeworkId }"
          :headers="getHeaders">
          <el-button size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
          </el-upload>
        </div>
      </el-card>
    </div>
        <div><el-card>
        <div>
          <h3>普通作业答案</h3>
          <p><span v-if="!editing" style="margin-top: 10px;">{{ homework.standardAnswer }}</span>
            <span v-else>
              <el-input v-model="homework.standardAnswer" type="textarea" autosize ></el-input>
            </span>
          </p>
        </div>
        <el-col :span="6" style="margin-top: 10px;">
          <el-button @click="toggleEditing">{{ editing ? '取消' : '编辑' }}</el-button>
          <el-button @click="saveAnswer" :disabled="!editing">保存</el-button>
        </el-col>
      </el-card></div>
      <div class="student-list">
        <h2>学生名单</h2>
        <el-button @click="checkRepeatability">重复检测</el-button>
      <el-card>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="ID" prop="studentId" width="150"></el-table-column>
          <el-table-column label="姓名" prop="name" width="150"></el-table-column>
          <el-table-column label="提交" prop="status" width="150">
          <template v-slot="scope">
          {{ scope.row.status === '0' ? '未提交' : (scope.row.status === '1' ? '已提交' : '其他状态') }}
          </template></el-table-column>
          <el-table-column label="作业内容" prop="content" width="150" v-if="false"></el-table-column>
          <el-table-column prop="file" width="150" v-if="false"></el-table-column>
          <el-table-column prop="excellent" width="150" v-if="false"></el-table-column>
          <el-table-column label="得分" prop="teacherGrade" width="100"></el-table-column>
          <el-table-column label="互评得分" prop="hupingGrade" width="100"></el-table-column>
          <el-table-column label="批改">
                <template v-slot="scope">
                <el-button @click="handleCorrect(scope.row)" :disabled="scope.row.status === '0'">详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background="true"
            layout="prev, pager, next"
            :total="total"
            v-model:currentPage="queryInfo.page"
            :page-size="queryInfo.size"
            @current-change="handlePageChange"
        />
      </el-card>
    </div>
    <h2>优秀作业展示</h2>
      <div><el-card>
        <el-table :data="excelentData" style="width: 100%">
          <el-table-column label="ID" prop="studentId" width="150"></el-table-column>
          <el-table-column label="姓名" prop="name" width="150"></el-table-column>
          <el-table-column label="总分" prop="scoreTotal" width="150"></el-table-column>
          <el-table-column prop="content" width="150" v-if="false"></el-table-column>
          <el-table-column prop="file" width="150" v-if="false"></el-table-column>
          <el-table-column label="详情">
                <template v-slot="scope">
                <el-button @click="handleDetail(scope.row)">查看详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background="true"
            layout="prev, pager, next"
            :total="excelentTotal"
            v-model:currentPageExce="queryExceInfo.page"
            :page-size="queryExceInfo.size"
            @current-change="handlePageExce"
        />
      </el-card></div>
    <h2>作业信息统计</h2>
    <el-tabs type="border-card">
      <el-tab-pane label="提交情况">
        <div id="pieChart1" style="width: 600px; height: 400px"></div>
      </el-tab-pane>
      <el-tab-pane label="成绩饼状图">
        <div id="pieChart2" style="width: 600px; height: 400px"></div>
      </el-tab-pane>
      <el-tab-pane label="成绩柱状图">
        <div id="barChart" style="width: 600px; height: 400px"></div>
      </el-tab-pane>
    </el-tabs>
    </div>
    <div>
    <el-dialog
            title="批改作业"
            v-model="correctDialogVisible"
            >
            <el-form :model="newStuHomework" label-width="140px">
                <el-form-item label="学生学号">
                <el-text>{{ newStuHomework.studentId }}</el-text>
                </el-form-item>
                <el-form-item label="学生答案">
                <el-text>{{ newStuHomework.content }}</el-text>
                </el-form-item>
                <el-form-item>
                  <el-upload
                  class="upload-demo"
                  ref="upload"
                  action=""
                  :file-list="HomeworkList"
                  :on-preview="handlePreview"
                  :auto-upload="false">
                </el-upload>
                </el-form-item>
                <el-form-item label="得分">
                <el-input v-model="newStuHomework.score"></el-input>
                </el-form-item>
                <el-form-item label="评语">
                <el-input v-model="newStuHomework.comment" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="优秀作业">
                <el-radio v-model="newStuHomework.radio" label="1" border>是</el-radio>
                <el-radio v-model="newStuHomework.radio" label="0" border>否</el-radio>
                <el-button type="primary" @click="saveExcellent">设置</el-button>
                </el-form-item>
                <el-form-item>
                <span class="dialog-footer">
                <el-button @click="correctDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="saveScore">保存</el-button>
                </span>
                </el-form-item>
            </el-form>
          </el-dialog>
          <el-dialog
            title="优秀作业"
            v-model="excellentDialogVisible"
            >
            <el-form :model="newExcellentHomework" label-width="140px">
                <el-form-item label="学生学号">
                <el-text>{{ newExcellentHomework.studentId }}</el-text>
                </el-form-item>
                <el-form-item label="学生姓名">
                <el-text>{{ newExcellentHomework.name }}</el-text>
                </el-form-item>
                <el-form-item label="学生答案">
                <el-text>{{ newExcellentHomework.content }}</el-text>
                </el-form-item>
                <el-form-item>
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  action=""
                  :file-list="ExceList"
                  :on-preview="handlePreview"
                  :auto-upload="false">
                </el-upload>
                </el-form-item>
                <el-form-item label="总分">
                <el-text>{{ newExcellentHomework.scoreTotal }}</el-text>
                </el-form-item>
            </el-form>
          </el-dialog>
      <el-dialog
            title="查重结果显示"
            v-model="repeatabilityDialogVisible">
            <el-text></el-text>
            <div><el-card>
            <el-table :data="similarityData" style="width: 100%">
              <el-table-column label="学生A" prop="studentA" width="150"></el-table-column>
              <el-table-column label="学生B" prop="studentB" width="150"></el-table-column>
              <el-table-column label="相似度" prop="similarity" width="150"></el-table-column>
          </el-table></el-card></div>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { getHomework } from '@/api/homeworkTeacher'
import { getHomeworkS } from '@/api/getHomeworkS'
import { saveScoreTea } from '@/api/teaScore'
import { saveExceHomework } from '@/api/saveExceHomework'
import { ElMessage } from 'element-plus'
import { deleteFile } from '@/api/deleteFile'
import * as echarts from 'echarts'
import { getGradeStatic } from '@/api/getGradeStatic'
import { getSimilar } from '@/api/getSimilar'
import { updateHomeworkT } from '@/api/updateHomeworkT'
import { getExcellentHomework } from '@/api/getExcellentHomework'

const route = useRoute()
const total = ref(0)
const excelentTotal = ref(0)
const store = useStore()
const tableData = ref([])
const excelentData = ref([])
const similarityData = ref([])
const currentPage = ref(1)
const currentPageExce = ref(1)
const upload = ref(null)

const isSwitchDisabled = ref(false)

const correctDialogVisible = ref(false)
const excellentDialogVisible = ref(false)
const repeatabilityDialogVisible = ref(false)

const homework = ref({
  homeworkId: '',
  teacherId: '',
  courseId: '',
  name: '',
  startTime: '',
  endTime: '',
  hupingStartTime: '',
  hupingEndTime: '',
  standardAnswer: '',
  profile: '',
  method: '0',
  anonymous: '0'
})

const newStuHomework = ref({
  homeworkId: route.params.homeworkId,
  content: '',
  studentId: '',
  score: '',
  comment: '',
  radio: -1
})

const newExcellentHomework = ref({
  homeworkId: route.params.homeworkId,
  name: '',
  content: '',
  studentId: '',
  scoreTotal: ''
})

const excellentStuHomework = ref({
  homeworkId: route.params.homeworkId,
  studentId: '',
  excellent: ''
})

const editing = ref(false)

const toggleEditing = () => {
  editing.value = !editing.value
  isSwitchDisabled.value = !isSwitchDisabled.value
}

const saveAnswer = async () => {
  const res = await updateHomeworkT(homework.value)
  if (res.data.code === 0) {
    ElMessage.success('设置成功！')
  }
  editing.value = !editing.value
  isSwitchDisabled.value = !isSwitchDisabled.value
}

const queryInfo = ref({
  homeworkId: route.params.homeworkId,
  page: currentPage,
  size: 10
})

const queryExceInfo = ref({
  homeworkId: route.params.homeworkId,
  page: currentPageExce,
  size: 10
})

const courseInfo = {
  homeworkId: route.params.homeworkId,
  homeworkName: '',
  courseId: '',
  teacherName: ''
}

const gradeRequest = {
  homeworkId: route.params.homeworkId
}

const gradeStatistic = ref({
  gradeStatisticA: 0,
  gradeStatisticB: 0,
  gradeStatisticC: 0,
  gradeStatisticD: 0,
  gradeStatisticNotSubmit: 0,
  gradeStatisticSubmit: 0
})

const getToken = computed(() => store.getters.getToken)

const getHeaders = computed(() => {
  return {
    Token: getToken.value
  }
})

const getDetail = async () => {
  const res = await getHomework(courseInfo)
  homework.value.courseId = res.data.data.courseId
  homework.value.endTime = res.data.data.endTime
  homework.value.homeworkId = res.data.data.homeworkId
  homework.value.hupingEndTime = res.data.data.hupingEndTime
  homework.value.hupingStartTime = res.data.data.hupingStartTime
  homework.value.name = res.data.data.name
  homework.value.profile = res.data.data.profile
  homework.value.standardAnswer = res.data.data.standardAnswer
  homework.value.startTime = res.data.data.startTime
  homework.value.teacherId = res.data.data.teacherId
  homework.value.method = res.data.data.method
  homework.value.anonymous = res.data.data.anonymous
  fileList.value = res.data.data.file.map(item => ({
    name: item.fileName,
    url: item.url
  }))
  console.log(res)
}

const handleDetail = (row) => {
  excellentDialogVisible.value = true
  newExcellentHomework.value.content = row.content
  newExcellentHomework.value.studentId = row.studentId
  newExcellentHomework.value.name = row.name
  newExcellentHomework.value.scoreTotal = row.scoreTotal
  ExceList.value = row.file.map(item => ({
    name: item.fileName,
    url: item.url
  }))
}

const handleCorrect = (row) => {
  correctDialogVisible.value = true
  newStuHomework.value.studentId = row.studentId
  newStuHomework.value.content = row.content
  newStuHomework.value.score = row.teacherGrade
  newStuHomework.value.radio = row.excellent
  HomeworkList.value = row.file.map(item => ({
    name: item.fileName,
    url: item.url
  }))
  excellentStuHomework.value.studentId = row.studentId
}

const checkRepeatability = async () => {
  repeatabilityDialogVisible.value = true
}

const handlePageChange = () => {
  getHomeworkStudent()
}

const handlePageExce = () => {
  getExcellentStudent()
}

const saveExcellent = async () => {
  excellentStuHomework.value.excellent = newStuHomework.value.radio
  const res = await saveExceHomework(excellentStuHomework.value)
  if (res.data.code === 0) {
    ElMessage.success('设置成功！')
  }
  getExcellentStudent()
  getHomeworkStudent()
}

const saveScore = async () => {
  const res = await saveScoreTea(newStuHomework.value)
  console.log(res)
  if (res.data.code === 0) {
    ElMessage.success('批改成功！')
  }
  correctDialogVisible.value = false
}

const del = ref({
  homeworkId: route.params.homeworkId,
  url: ''
})

const fileList = ref([])
const HomeworkList = ref([])
const ExceList = ref([])

const submitUpload = () => {
  upload.value.submit()
}

const handleRemove = (file) => {
  del.value.url = file.url
  const res = deleteFile(del.value)
  console.log(res)
}

const handlePreview = (file) => {
  window.open(file.url, '_blank')
}

const getHomeworkStudent = async () => {
  const res = await getHomeworkS(queryInfo.value)
  tableData.value = res.data.data.rows
  total.value = res.data.data.total
}

const getExcellentStudent = async () => {
  const res = await getExcellentHomework(queryExceInfo.value)
  excelentData.value = res.data.data.rows
  excelentTotal.value = res.data.data.total
}

const getSimilarity = async () => {
  const res = await getSimilar(gradeRequest)
  similarityData.value = res.data.data
}

const getStatus = async () => {
  const res = await getGradeStatic(gradeRequest)
  gradeStatistic.value = res.data.data
}

const generateChart = async () => {
  const chart = echarts.init(document.getElementById('pieChart1'))

  const option = {
    title: {
      text: '作业完成情况',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: ['未交作业', '已交作业']
    },
    series: [
      {
        name: '作业完成情况',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '30',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: gradeStatistic.value.gradeStatisticNotSubmit, name: '未交作业' },
          { value: gradeStatistic.value.gradeStatisticSubmit, name: '已交作业' }
        ]
      }
    ]
  }

  chart.setOption(option)
}

const generatePieChart = () => {
  const chart = echarts.init(document.getElementById('pieChart2'))

  const option = {
    title: {
      text: '成绩分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: ['优秀', '良好', '中等', '及格', '不及格']
    },
    series: [
      {
        name: '成绩分布',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '30',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: gradeStatistic.value.gradeStatisticA, name: '优秀' },
          { value: gradeStatistic.value.gradeStatisticB, name: '良好' },
          { value: gradeStatistic.value.gradeStatisticC, name: '中等' },
          { value: gradeStatistic.value.gradeStatisticD, name: '及格' },
          { value: gradeStatistic.value.gradeStatisticN, name: '不及格' }
        ]
      }
    ]
  }

  chart.setOption(option)
}

const generateBarChart = () => {
  const chart = echarts.init(document.getElementById('barChart'))

  const option = {
    title: {
      text: '成绩分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['优秀', '良好', '中等', '及格', '不及格']
    },
    yAxis: {
      type: 'value',
      minInterval: 1
    },
    series: [
      {
        name: '人数',
        type: 'bar',
        data: [gradeStatistic.value.gradeStatisticA, gradeStatistic.value.gradeStatisticB, gradeStatistic.value.gradeStatisticC, gradeStatistic.value.gradeStatisticD, gradeStatistic.value.gradeStatisticNotSubmit]
      }
    ]
  }

  chart.setOption(option)
}

onMounted(getDetail)
onMounted(getHomeworkStudent)
onMounted(getExcellentStudent)
onMounted(() => {
  getStatus().then(() => {
    generateBarChart()
    generatePieChart()
    generateChart()
  })
})
onMounted(getDetail)
onMounted(getSimilarity)
</script>

<style scoped>
.course-info {
  margin-bottom: 20px;
}

.course-info span {
  margin-right: 10px;
}

.course-description {
  margin-top: 10px;
}

.student-list {
  margin-top: 20px;
}

table {
  width: 100%;
}

th, td {
  text-align: center;
  padding: 5px;
  border: 1px solid #ccc;
}

th {
  background-color: #f0f0f0;
}
.answerSize {
    margin-top: 10px;
}
.upload-demo{
  margin-top: 5px;
}
.input-group {
  margin-bottom: 10px;
}
</style>
